package org.nofs;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.net.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class Empower {
    private static final String API_URL = "http://auth.curcur.cn/activation_jar.php?act=activation&";
    private static final File CODE_FILE = new File("code.txt");
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    private static String code = null;
    private static String end_date = null;
    private static String device = null;
    public static void main(String[] args) {
        auth();
    }

    public static boolean auth() {
        LocalDateTime currentTime = LocalDateTime.now();
        String formattedTime = currentTime.format(FORMATTER);
        try {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
            byte[] macAddress = networkInterface.getHardwareAddress();
            if (macAddress != null) {
                StringBuilder macAddressStr = new StringBuilder();
                for (int i = 0; i < macAddress.length; i++) {
                    macAddressStr.append(String.format("%02X%s", macAddress[i], (i < macAddress.length - 1) ? "-" : ""));
                }
                System.out.println("MAC Address: " + macAddressStr.toString());
                device = macAddressStr.toString();
            }
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
            System.out.println("获取设备信息失败");
            System.exit(0);
        }
        String result = empower();
        assert result != null;
        if (result.equals("200")) {
            System.out.println("------------------[success] 已成功授权,到期时间: " + end_date + "------------------");
            writeCodeToFile();
            return true;
        } else if (result.equals("201") || result.equals("202")) {
            System.out.println("------------------[error] 授权码过期||不存在||已被设备激活,请联系QQ: 9379401 以获得支持------------------");
            if (CODE_FILE.exists()) {
                if (CODE_FILE.delete()) {
                    System.out.println("------------------[success] 授权码文件已成功清理------------------");
                } else {
                    System.out.println("------------------[error] 授权码文件清理失败------------------");
                }
            }
            return false;
        }
        return false;
    }

    public static String empower() {
        if (CODE_FILE.exists()) {
            try (Scanner scanner = new Scanner(CODE_FILE)) {
                if (scanner.hasNext()) {
                    code = scanner.next();
                    System.out.println("[info] 检测到授权码文件,已为您自动填充: " + code);
                    return sendCode(code);
                } else {
                    System.out.println("[error] 授权码文件是空的，请确保文件中包含有效的授权码");
                }
            } catch (FileNotFoundException e) {
                System.out.println("[error] 找不到授权码文件");
            }
        } else {
            try (Scanner scanner = new Scanner(System.in)) {
                System.out.println("------------------[wait] 未检测到授权码文件,您需要手动输入授权码------------------");
                System.out.println("------------------[wait] 当前程序未授权,请联系QQ: 9379401 获取授权码------------------");
                System.out.print("请输入授权码以激活您的程序: ");
                code = scanner.next();
                return sendCode(code);
            }
        }
        return null;
    }


    public static String sendCode(String code) {
        try {
            URL url = new URL(API_URL + "code=" + code + "&device=" + device);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode jsonNode = mapper.readTree(response.toString());
                    String msgCode = jsonNode.get("code").asText();
                    try {
                        end_date = jsonNode.get("end_date").asText();
                    } catch (Exception e) {
                        System.out.println("------------------[error] 未获取到有效的授权截止日期------------------");
                    }
                    return msgCode;
                }
            }
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void writeCodeToFile() {
        // 创建code.txt内容为code
        try (FileWriter writer = new FileWriter(CODE_FILE)) {
            writer.write(code);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
